import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { defaultRoutes } from '@/router/default'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/largeScreen'] // 白名单,里面的路由可不登录访问

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // 判断Cookie里面有没有Token
  const hasToken = getToken()
  // 如果有Token
  if (hasToken && hasToken !== 'undefined') {
    const hasUserInfo = store.getters.hasUserInfo
    if (hasUserInfo === '0') {
      try {
        // 获取用户信息
        await store.dispatch('user/getInfo')
        // 获取路由信息(此处只获取一级目录)
        const routers = await store.dispatch('permission/getRouters')
        router.addRoutes(routers)
        // 增加默认路由
        router.addRoutes(defaultRoutes)

        // if (to.path === '/') {
        //   store.dispatch('permission/setActiveMenu', '/homePage')
        //   next({ path: '/homePage' })
        // } else {
        store.dispatch('permission/setActiveMenu', '/' + to.path.split('/')[1])
        next({ ...to, replace: true })
        // }
      } catch (error) {
        // 重置Token，跳转到登录页
        await store.dispatch('user/resetToken')
        // Message.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
      }
    }
    if (hasUserInfo === '1') {
      if (to.path === '/productionManage/start' || to.path === '/productionManage/report') {
        if (!store.state.productionManage.start.id) {
          next({ path: '/productionManage/startMain' })
        } else {
          next()
        }
      } else {
        next()
      }
    }
  } else {
    // 如果无Token
    if (whiteList.indexOf(to.path) !== -1) { // 如果路由在白名单里
      next()
    } else {
      // 跳转到登录页
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  store.state.settings.footBar = []
  NProgress.done()
})
